package os;

/**
 * Mini monitor for the MiniOS
 */
public class MiniMonitor
{
	/**
	 * Inside monitor
	 */
	private boolean in;
	
	/**
	 * The number of threads trying to enter the monitor
	 */
	private int inCount;
	/**
	 * Resource allocated
	 */

	public MiniMonitor()
	{
		inCount = 0;
	}

	/**
	 * Enter Monitor critical section
	 */
	public synchronized void enter()
	{
		synchronized(this)
		{
			inCount++;
		}
		while (this.in)
		{
			try
			{
				wait();
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		in = true;
	}

	/**
	 * leave Monitor critical section
	 */
	public synchronized void leave()
	{
		synchronized(this)
		{
			inCount--;
		}
		if (inCount > 0)
			notifyAll();
		in = false;
	}
}
